const Service = require('egg').Controller;
class HomeService extends Service {
  async addToCart() {
    const {ctx,app} = this;
    // 1. 判断是第一次加入吗
    const {user_id,shop_id} = ctx.request.body;
    const isHave = await app.mysql.get('carts', {user_id, shop_id})
    let data;
    if(isHave) {
        // 如果已经加入过 则count++
        data =await app.mysql.update('carts', {id:isHave.id, count: isHave.count+=1})
    } else {
        // 第一次加入则插入数据
        data = await app.mysql.insert('carts', {user_id,shop_id,count:1})
    }
    return data
  }
  async setCartCount() {
      const {ctx,app}  = this;
      const {id, count} = ctx.request.body;
      const data = await app.mysql.update('carts',{id, count})
      return data
  }
  // 获取购物车列表
  async getCartList() {
    const {ctx,app} = this;
    const {user_id} = ctx.query;
    const data = await app.mysql.select('carts', {user_id})
    const pAll = data.map(item => {
      return app.mysql.get('shops',{id:item.shop_id})
    })
    const shopData = await Promise.all(pAll)
    const newData = data.map((item,index) => {
      return {
        ...shopData[index],
        ...item,
      }
    })
    return newData
  }
  async delCartList() {
    const {ctx,app} = this;
    const {id} = ctx.params;
    const data = await app.mysql.delete('carts',{id})
    return data
  }
}

module.exports = HomeService;